// Copyright 2019 Age of Minds inc.

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0

// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "easy_grpc/server/credentials.h"
#include <string>

namespace easy_grpc {
namespace server {

Credentials::Credentials() : creds_(nullptr) {}

Credentials::Credentials(const char* root_certs, const char* private_key, const char* trust_chain,
                         grpc_ssl_client_certificate_request_type client_requirements) {
  grpc_ssl_pem_key_cert_pair key_cert_pair;
  key_cert_pair.private_key = private_key;
  key_cert_pair.cert_chain = trust_chain;

  grpc_ssl_server_certificate_config* config = grpc_ssl_server_certificate_config_create(root_certs, &key_cert_pair, 1);
  grpc_ssl_server_credentials_options* options =
      grpc_ssl_server_credentials_create_options_using_config(client_requirements, config);
  creds_ = grpc_ssl_server_credentials_create_with_options(options);
}

Credentials::~Credentials() {
  if (creds_ != nullptr) {
    grpc_server_credentials_release(creds_);
  }
}

Credentials::Credentials(Credentials&& rhs) {
  creds_ = rhs.creds_;
  rhs.creds_ = nullptr;
}

Credentials& Credentials::operator=(Credentials&& rhs) {
  if (creds_ != nullptr) {
    grpc_server_credentials_release(creds_);
  }
  creds_ = rhs.creds_;
  rhs.creds_ = nullptr;
  return *this;
}

}  // namespace server
}  // namespace easy_grpc